<?php

namespace app\common\cachemodel\ai_chat_room;

use app\common\cachemodel\Recode;
use app\common\model\BaseCache;
use traits\model\SoftDelete;
use XznsTools\cache\CacheManage;

class AiChatRecord extends BaseCache
{
    protected $table = 'ai_chat_room.ai_chat_record';

    protected $cacheModel = 'ai_chat_room.chat_id';

    use SoftDelete;

    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['uid'], [$id => $data['update_time']]);
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 更新 信息
     * @param int $roomId
     * @param int $uid
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $roomId, int $uid, array $data)
    {
        try
        {
            $data['update_time'] = time();
            $this->where(['id' => $roomId])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $roomId)->rmCache();
            // 更新排序顺序
            $this->listDataAdd($uid, [$roomId => $data['update_time']]);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 更新 信息2
     * @param int $roomId
     * @param array $data
     * @return bool
     */
    public function UpdateData2(int $roomId, array $data)
    {
        try
        {
            $this->where(['id' => $roomId])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $roomId)->setCacheTime(10)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['uid' => $type[0]];
        }
        $field = 'uid,config_id,sid,new_msg,avatar,name,type,last_chat_detail_id,last_chat_detail_time,create_time,update_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->order('update_time', $sortType)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'config_id', 'sid', 'new_msg', 'type', 'uid', 'last_chat_detail_id', 'last_chat_detail_time', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * 添加默认 系统推荐 聊天室
     * @return array
     */
    public function addDefaultRoom(int $uid, array $defaultRoomConfig)
    {
        $nowTime = time();
        $insertConfig = [
            'uid' => $uid,
            'type' => $defaultRoomConfig['type'],
            'config' => json_encode(['config' => $defaultRoomConfig['config'], 'desc' => $defaultRoomConfig['desc']], JSON_UNESCAPED_UNICODE),
            'sl_id' => $defaultRoomConfig['sl_id'],
            'create_time' => $nowTime,
            'update_time' => $nowTime,
        ];
        $configId = (new AiChatUserConfig())->SaveData($insertConfig);

        $initChatData = [
            'uid' => $uid,
            'config_id' => $configId,
            'avatar' => $defaultRoomConfig['avatar'],
            'name' => $defaultRoomConfig['name'],
            'type' => $defaultRoomConfig['type'],
            'sid' => $defaultRoomConfig['id'],
            'new_msg' => 0,
            'last_chat_detail_id' => 0,
            'last_chat_detail_time' => 0,
            'create_time' => $nowTime,
            'update_time' => $nowTime,
        ];
        $id = $this->SaveData($initChatData);

        $initChatData['id'] = $id;
        return $initChatData;
    }

    /**
     * 对话记录删除
     * @param int $uid
     * @param int $roomId
     * @return bool
     * @throws \Exception
     */
    public function delRoom(int $uid, int $roomId): bool
    {
        try
        {
            $this::destroy($roomId);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $roomId)->rmCache();
        }
        catch (\Exception $e)
        {
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');

        return true;
    }

    /**
     * 分页数据 重组
     * @param array $data
     * @return array
     */
    public function pageDataResert(array $data)
    {
        $aiChatUserConfigModel = new AiChatUserConfig();
        $aiChatTagModel = new AiChatTag();
        $aiChatRecordDetailsModel = new AiChatRecordDetails();
        $configData = config('ai_chat_room');
        $resData = [];
        foreach ($data as $datum)
        {
            $roomTypeConfig = $configData['type_list'][$datum['type']];
            $tagIcons = [];
            if ($datum['sid'])
            {
                $tagIcons[] = $configData['system_tag_icon'];
            }
            $chatConfig = $aiChatUserConfigModel->getInfoById($datum['config_id']);
            $chatData = $datum['last_chat_detail_id'] ? $aiChatRecordDetailsModel->getInfoById($datum['last_chat_detail_id']) : null;
            $tagIcons[] = $roomTypeConfig['tag_icon'];
            $resData[] = [
                'heal_chat_id' => $datum['id'],
                'avatar' => $datum['avatar'],
                'name' => $datum['name'],
                'message' => $chatData['content'] ?? '',
                'desc' => $aiChatTagModel->getChatDescData($datum['type'], $chatConfig['config']['config']),
                'msg_num' => $datum['new_msg'],
                'tag_list' => $tagIcons,
                'is_del' => 1,
            ];
        }

        return $resData;
    }

    /**
     * 获取 系统推荐用户数据
     * @param array $userInfo
     * @return array
     * @throws \Exception
     */
    public function getDefaultUserData(array $userInfo)
    {
        $configData = config('ai_chat_room');
        //  判断 需要添加的伙伴
        $defaultUserData = $configData['default_user'];

        $lastData = (new AiChatLastSendTimeRecord())->getDataInfo($userInfo['id']);
        $useIdType = $lastData['extend']['use_type'] ?? [];
        $useIdType = array_keys($useIdType);
        foreach ($useIdType as $useTypeItem)
        {
            unset($defaultUserData[$useTypeItem]);
        }
        $resData = [];
        if ($defaultUserData)
        {   // 获取未删除 的数据
            $defaultSex = 1;    // 1=>男 2=>女 默认 男
            if ($userInfo['rid'])
            {
                $recodeInfo = (new Recode())->getInfoById($userInfo['rid']);
                $type = (int)($recodeInfo['type'] ?? 1);
                $defaultSex = $type === 2 ? 1 : 2;
            }
            $aiChatTagModel = new AiChatTag();
            foreach ($defaultUserData as $id => $item)
            {
                $dataItem = $item[$defaultSex];
                $tagIcons = [$configData['system_tag_icon']];
                $tagIcons[] = $configData['type_list'][$dataItem['type']]['tag_icon'];
                $resData[] = [
                    'heal_chat_id' => $dataItem['id'],
                    'avatar' => $dataItem['avatar'],
                    'name' => $dataItem['name'],
                    'message' => '',
                    'desc' => $aiChatTagModel->getChatDescData($dataItem['type'], $dataItem['config']),
                    'msg_num' => 0,
                    'tag_list' => $tagIcons,
                    'is_del' => 0,
                ];
            }
        }
        return $resData;
    }

    public function setPageLimit(int $limit)
    {
        $this->pageLimit = $limit;
        return $this;
    }
}